//
//  RCollectListViewController.m
//  iMoive
//
//  Created by 侯伟 on 2021/8/27.
//

#import "RCollectListViewController.h"
#import "RSRefreshTableView.h"
#import "RCollectTableViewCell.h"

#import "RVideoDetailsViewController.h"

#import "RVideoObj.h"

@interface RCollectListViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong) MyLinearLayout *contentLayout;

/// 影片
@property(nonatomic,strong)RSRefreshTableView* tableView;

//底部
@property(nonatomic,strong) MyLinearLayout *bottomLayout;

//编辑
@property(nonatomic,strong) UIButton* editBtn;

//全选
@property(nonatomic,strong) UIButton* allBtn;

//删除
@property(nonatomic,strong) UIButton* delBtn;

//视频
@property(nonatomic,strong)NSMutableArray* movies;

@end

@implementation RCollectListViewController

- (BOOL)isTableEditing{
    if(self.editBtn){
        return self.editBtn.selected;
    }
    return NO;
}

- (void)loadView{
    [super loadView];
    self.view.backgroundColor = UIColor.whiteColor;
    
    // 线性布局
    MyLinearLayout *contentLayout = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Vert)];
    contentLayout.myMargin = 0;
    [self.view addSubview:contentLayout];
    _contentLayout = contentLayout;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupNavBar];
    
    [self setupSubView];
    
    [self reloadData];
}

- (void)setupNavBar{
    self.navigationItem.title = @"我的收藏";
    
    UIButton* editBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [editBtn setTitle:@"编辑" forState:UIControlStateNormal];
    [editBtn setTitle:@"取消" forState:UIControlStateSelected];
    [editBtn setTitleColor:COLOR_WHITE forState:UIControlStateNormal];
    [editBtn addTarget:self action:@selector(editClicked:) forControlEvents:UIControlEventTouchUpInside];
    editBtn.titleLabel.font = FONTMID(15);
    editBtn.myHeight = PX(44);
    editBtn.myWidth = PX(44);
    _editBtn = editBtn;
    UIBarButtonItem* editItem = [[UIBarButtonItem alloc] initWithCustomView:editBtn];
    self.navigationItem.rightBarButtonItem = editItem;
}

-(void)setupSubView{
    
    //列表
    RSRefreshTableView* tableView = [[RSRefreshTableView alloc] initWithFrame:CGRectMake(0, 0, self.view.rs_width, SCREEN_HEIGHT - IPHONE_NAVIGATION_BAR_HEIGHT) style:UITableViewStylePlain];
    tableView.refreshEnabled = NO;
    tableView.loadMoreEnabled = NO;
    
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.rowHeight = PX(157)+16;
    tableView.backgroundColor = COLOR_BACKGEOUND;
    tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [tableView registerClass:NSClassFromString(collectCell) forCellReuseIdentifier:collectCell];
    tableView.myMargin = 0;
    tableView.weight = 1.0;
    [self.contentLayout addSubview:tableView];
    _tableView = tableView;

    MyLinearLayout* bottomLayout = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Horz)];
    bottomLayout.padding = UIEdgeInsetsMake(8, 16, isIphoneX?IPHONE_BOTTOM_SAFEINSET:8, 16);
    bottomLayout.myHeight = IPHONE_TAB_BAR_HEIGHT;
    bottomLayout.gravity = MyGravity_Horz_Fill;
    bottomLayout.myMargin = 0;
    [self.contentLayout addSubview:bottomLayout];
    _bottomLayout = bottomLayout;
    
    UIButton* allBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [allBtn setTitle:@"全选" forState:UIControlStateNormal];
    [allBtn setImage:[UIImage imageNamed:@"common_select_n"] forState:UIControlStateNormal];
    [allBtn setImage:[UIImage imageNamed:@"common_select_h"] forState:UIControlStateSelected];
    [allBtn setTitleColor:COLOR_GRAY_BASE forState:UIControlStateNormal];
    allBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 4);
    allBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 4, 0, 0);
    allBtn.titleLabel.font = FONT_FIT(15);
    [allBtn addTarget:self action:@selector(allSelectClicked:) forControlEvents:UIControlEventTouchUpInside];
    allBtn.myMargin = 0;
    [allBtn sizeToFit];
    [bottomLayout addSubview:allBtn];
    _allBtn = allBtn;
    
    UIButton* delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [delBtn setTitle:@"删除(0)" forState:UIControlStateNormal];
    [delBtn setTitleColor:COLOR_RED forState:UIControlStateNormal];
    delBtn.titleLabel.font = FONT_FIT(15);
    [delBtn addTarget:self action:@selector(deleteClicked:) forControlEvents:UIControlEventTouchUpInside];
    delBtn.myMargin = 0;
    [delBtn sizeToFit];
    [bottomLayout addSubview:delBtn];
    _delBtn = delBtn;
    
    self.bottomLayout.visibility = MyVisibility_Gone;
}

#pragma mark --loadData
- (void)reloadData{
    
    RLMResults* ret = [RVideoObj objectsWhere:@"isCollect = %d",YES];
    
    NSMutableArray* objs = [NSMutableArray array];
    for (int i = 0; i < ret.count; i++) {
        [objs addObject:ret[i]];
    }
    self.movies = objs;
    [self.tableView reloadData];
}

#pragma mark -- actions

- (void)editClicked:(UIButton*)sender{
    sender.selected = !sender.selected;
    self.bottomLayout.visibility = sender.selected?MyVisibility_Visible:MyVisibility_Gone;
    
    for (RVideoObj* obj in self.movies) {
        obj.isSelected = NO;
    }
    
    self.allBtn.selected = NO;
    
    [self.delBtn setTitle:@"删除(0)" forState:UIControlStateNormal];
    
    [self.tableView reloadData];
}

- (void)allSelectClicked:(UIButton*)sender{
    sender.selected = !sender.selected;
    for (RVideoObj* obj in self.movies) {
        obj.isSelected = sender.selected;
    }
    if(sender.selected){
        [self.delBtn setTitle:[NSString stringWithFormat:@"删除(%ld)",self.movies.count] forState:UIControlStateNormal];
    }else{
        [self.delBtn setTitle:@"删除(0)" forState:UIControlStateNormal];
    }
    
    [self.tableView reloadData];
}

- (void)deleteClicked:(UIButton*)sender{
    
    for (RVideoObj* obj in self.movies) {
        if(obj.isSelected){
            RLMResults* ret = [RVideoObj objectsWhere:@"id = %@ and isCollect = %d ",obj.id,YES];
            [[RLMRealm defaultRealm] beginWriteTransaction];
            [[RLMRealm defaultRealm] deleteObjects:ret];
            [[RLMRealm defaultRealm] commitWriteTransaction];
        }
    }
    
    [self reloadData];
    
    [self editClicked:self.editBtn];
}

- (void)checkSelectState{
    
    NSInteger selectCount = 0;
    for (RVideoObj* obj in self.movies) {
        if(obj.isSelected){
            selectCount += 1;
        }
    }
    self.allBtn.selected = selectCount == self.movies.count;
    
    [self.delBtn setTitle:[NSString stringWithFormat:@"删除(%ld)",selectCount] forState:UIControlStateNormal];
}

#pragma mark --UITableViewDelegate  UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.movies.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  
    RVideoObj* movie = [self.movies objectAtIndex:indexPath.row];

    RCollectTableViewCell* movieCell = [tableView dequeueReusableCellWithIdentifier:collectCell forIndexPath:indexPath];
    movieCell.editable = [self isTableEditing];
    movieCell.movie = movie;
    movieCell.selectBlock = ^(BOOL Bool) {
        [self checkSelectState];
    };
    return movieCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    RVideoObj* video = [self.movies objectAtIndex:indexPath.row];
    
    if([self isTableEditing]){
        video.isSelected = !video.isSelected;
        [self checkSelectState];
        
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationAutomatic)];
    }else{
        /// To Details
        RVideoDetailsViewController* details = [RVideoDetailsViewController new];
        details.video = video;
        [UIViewController showViewController:details animated:YES];
    }
}

@end
